package chaw.android.train;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import chaw.android.util.HttpRequestManager;
import chaw.android.util.LoadBitMap;
import chaw.android.util.Preferences;
import chaw.android.util.ServerURL;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class ChatListActivity extends ListActivity{
	private ArrayList<JSONObject> json_list;
	private ArrayList<ChatItem> chat_list;
	private ChatListItemAdapter nadapter;
	private ImageButton btnCreateRoom;
	private String downloadResult = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.chat_list);
	    
	    btnCreateRoom = (ImageButton) findViewById(R.id.btnCreateRoom);
	    btnCreateRoom.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(), CreateRoomActivity.class);
				intent.putExtra("isInvite", false);
				startActivity(intent);
			}
		});
	}
	
	private void setListView(){
		chat_list = new ArrayList<ChatItem>();
	    chat_list.clear();
	    DownloadAsynkTask task = new DownloadAsynkTask();
		String[] params = new String[]{ServerURL.roomList, "user_id", Preferences.getValue(getBaseContext(), "user_id"), "uuid_check", Preferences.getValue(getBaseContext(), "uuid") };
		task.execute(params);
	}

	@Override
	public void onListItemClick(ListView parent, View v, int position, long id){
		super.onListItemClick(parent, v, position, id);
		Intent chatIntent = new Intent(getBaseContext(), ChatRoomActivity.class);
		chatIntent.putExtra("isChat", true);
		ChatItem selectedItem = (ChatItem) parent.getItemAtPosition(position);
		chatIntent.putExtra("roomId", selectedItem.getId());
		startActivity(chatIntent);
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		setListView();
	}
	
	private class ChatItem{
		private String room_id;
		private String room_name;
		private String room_badge;
		private Bitmap image_thumb;
		public ChatItem(String id, String name, String badge, Bitmap thumbnail){
			room_name = name;
			room_id = id;
			room_badge = badge;
			image_thumb = thumbnail;
		}
		public String getId(){
			return room_id;
		}
		public String getName(){
			return room_name;
		}
		public String getBadge(){
			return room_badge;
		}
		public Bitmap getImage(){
			return image_thumb;
		}
	}
	
	private class ChatListItemAdapter extends ArrayAdapter<ChatItem>{
		private ArrayList<ChatItem> items;
		int layout;
		
		public ChatListItemAdapter(Context ctx, int layout, ArrayList<ChatItem> data){
			super(ctx, layout, data);
			this.items = data;
			this.layout = layout;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent){
			View v = convertView;
			if(v == null){
				LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(layout, null);
			}
			ChatItem eachRoom = items.get(position);
			
			if(eachRoom != null){
				//if
				if(eachRoom.getImage() != null){
					((ImageView)v.findViewById(R.id.userPhoto)).setImageBitmap(eachRoom.getImage());
				}
				else{
					((ImageView)v.findViewById(R.id.userPhoto)).setImageResource(R.drawable.icon_noprofile_m);
				}
				
				((TextView)v.findViewById(R.id.speakers)).setText(eachRoom.getName());
				
				if(eachRoom.getBadge().equalsIgnoreCase("") || eachRoom.getBadge().equalsIgnoreCase("0")){
					((Button)v.findViewById(R.id.badge)).setText("");
					((Button)v.findViewById(R.id.badge)).setBackgroundDrawable(null);
				}
				else{
					((Button)v.findViewById(R.id.badge)).setText(eachRoom.getBadge());
					((Button)v.findViewById(R.id.badge)).setBackgroundResource(R.drawable.bg_count);
				}
			}
			return v;
		}
	}
	
	private class DownloadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
//			Log.d("ChatList", "room list" + result);
			downloadResult = result;
			ImageAsynkTask task = new ImageAsynkTask();
			task.execute(new String[]{result});
			nadapter = new ChatListItemAdapter(getBaseContext(), R.layout.chat_list_row, chat_list);
			ListView lv = getListView();
			lv.setAdapter(nadapter);
		}
	}
	

	private class ImageAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			JSONArray json_arr;
			try {
				json_arr = new JSONArray(urls[0]);
				for(int i = 0 ; i < json_arr.length(); i++){
					JSONObject json_obj = (JSONObject) json_arr.get(i);
					JSONArray usersInRoom = json_obj.getJSONArray("users");
					JSONObject someUser = usersInRoom.getJSONObject(0);
					String speakers = "";
					Bitmap thumb = null;
					if(someUser.getString("user_id").equalsIgnoreCase(Preferences.getValue(getBaseContext(), "user_id")) && usersInRoom.length() > 1)
						someUser = usersInRoom.getJSONObject(1);
					if(someUser.has("image_thumb_url") && !someUser.getString("image_thumb_url").equalsIgnoreCase("null")){
						String imageUrl = someUser.getString("image_thumb_url");
						thumb = LoadBitMap.fromURL(imageUrl);
					}

					if(usersInRoom.length() > 2)
						speakers = someUser.getString("nick_name") + "님 외 " + ( usersInRoom.length() - 2) + "명";
					else
						speakers = someUser.getString("nick_name") + "님";
					
					String badgeCount = "";
					if(!json_obj.get("badge").toString().equals("") && !json_obj.get("badge").toString().equals("null")){
						badgeCount = json_obj.get("badge").toString();
					}
							
					chat_list.add(new ChatItem(json_obj.get("room_id").toString(), speakers, badgeCount, thumb));
				}
			}catch(Exception e){
				e.printStackTrace();
			}
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if(nadapter != null){
				nadapter.notifyDataSetChanged();
			}
			
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu){
		menu.add(0, 1 , 0 , "채팅방 수정");
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()){
		case 1:
			if(downloadResult != null){
				Intent intent = new Intent(getBaseContext(), ModifyChatListActivity.class);
				intent.putExtra("modify_list", downloadResult);
				startActivity(intent);
				return true;
			}
			else{
				return false;
			}
		}
		return false;
	}
}
